import axios from 'axios'
import qs from 'qs'
import router from '@/router/router'
import store from '@/store'
import {Message, MessageBox} from 'element-ui'
import {getStore} from '@/util/store'
import { baseUrl, apiPrefix } from '@/config/env';

let show_msgBox = false; // 弹窗提示

let cancel, promiseArr = {};
const CancelToken = axios.CancelToken;
var myaxios = axios.create({
  // baseURL: baseUrl
});
// axios.defaults.withCredentials = true;
//请求拦截器
// myaxios.interceptors.request.use(config => {  
  //发起请求时，取消掉当前正在进行的相同请求
  // if (promiseArr[config.url]) {
  //   promiseArr[config.url]('操作取消');
  //   promiseArr[config.url] = cancel;
  // } else {
  //   promiseArr[config.url] = cancel;
  // }
//   return config;
// }, error => {
//   return Promise.reject(error)
// })

//响应拦截器即异常处理
myaxios.interceptors.response.use(response => {
  return response
}, err => {
  console.log(err);
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        err.message = '错误请求'
        break;
      case 401:
        err.message = '未授权，请重新登录'
        break;
      case 403:
        err.message = '拒绝访问'
        break;
      case 404:
        err.message = '请求错误,未找到该资源'
        break;
      case 405:
        err.message = '请求方法未允许'
        break;
      case 408:
        err.message = '请求超时'
        break;
      case 500:
        err.message = '服务器端出错'
        break;
      case 501:
        err.message = '网络未实现'
        break;
      case 502:
        err.message = '网络错误'
        break;
      case 503:
        err.message = '服务不可用'
        break;
      case 504:
        err.message = '网络超时'
        break;
      case 505:
        err.message = 'http版本不支持该请求'
        break;
      default:
        err.message = `连接错误${err.response.status}`
    }
  } else {
    err.message = "连接到服务器失败"
  }
  // Message.error(err.message)

  return Promise.resolve(err.response)
});

function Client (method, action, params, callback, failback, options, type) {
  let url = action;
  if(action.indexOf('geoserver') == -1){
    url = apiPrefix + action
  }
  // axios传递的请求参数是json格式
  // 如果后端接口要求formData,则post传参是要序列化 qs.stringify(params);
    var default_options = {
      method: method,
      // url: process.env.BASE_API + action,
      url: url,
      data: method === 'post' || method === 'put' ? (params ? params : null) : null,
      params: method === 'get' || method === 'delete' ?  params : null,
      timeout: 30000,
      headers: {},
      dataType: 'json',
      cancelToken: new CancelToken(c => {
        cancel = c
      })
    };

    // const TENANT_ID = getStore({name: 'tenantId'})
    const TENANT_ID = '1';
    if (TENANT_ID) {
      default_options.headers['TENANT-ID'] = TENANT_ID // 租户ID
    }
    // const CLIENT_ID = getStore({name: 'client_id'});
    const CLIENT_ID = 'pig';
    if (CLIENT_ID) {
      default_options.headers['CLIENT-ID'] = CLIENT_ID // 用户类型
    }
    // var token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJoa3kiLCJleHAiOjE3MDI2MjczNjF9.YyQCvj64lid3M95r_8xTTGsqoK3qrv5-cJePP25b8Sk';//store.getters.access_token;
    var token = localStorage.getItem('access_token');
    // 如果存在token，在请求头设置token
    if (token) {
      default_options.headers['Authorization'] = token;//'Bearer ' + token;
    }else{
      default_options.headers['Authorization'] = 'Basic cGlnOnBpZw==';
    }

    // 如果参数中有formData的属性，就用formData的方式传参
    if(params){
      if(params.hasOwnProperty('formData')){
        default_options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        default_options.data = qs.stringify(params.formData);
        let opt = {};
        for(let key in params){
          if(key != 'formData'){
            opt[key] = params[key];
          }
        }
        default_options.params = opt
      }
    }

    // 扩展参数
    var new_options;
    let opt = options;
    if(typeof(callback) == 'object'){
      opt = callback;
    }
    if (opt) {
      new_options = Object.assign({}, default_options, opt);
    } else {
      new_options = default_options;
    }

    // 请求
    return new Promise((resolve, reject) => {
      myaxios(new_options).then(response => {
        // const status = Number(response.status) || 200;
        let {status, data} = response; 
        if(status == 200){
          resolve(data);
          if(typeof(callback) === 'function'){
            callback(data, '请求成功');
          } 
          return;
        }else if (status == 401) {
          if(action == '/token'){
            Message.error(data.detail)
            return;
          }
          // store.dispatch('LogOut').then(() => {
          //   window.location.reload()
          // })        
          return;
        } else {
          Message.error('请求失败！');
          if (typeof(failback) === 'function') {
            failback(msg);
          }
          // return;
        }
      }).catch(error => {
        // Message.error(error);
        if (typeof(failback) === 'function') {
          failback(error);
        }
        reject(error);
        return;
      })
    });
}

export default Client;